package util;

import pojo.Grade;

public class GradeDBUtil extends DBUtil {
    //根据gno查询班级
    public Grade getGradeByGno(Integer gno) {
        Grade grade = null;
        try {
            getConn();
            String sql = "select gno,gname,gdesc  from grade where gno=" + gno;
            st = conn.createStatement();
            rs = st.executeQuery(sql);
            if (rs.next()) {
                gno = rs.getInt("gno");
                String gname = rs.getString("gname");
                String gdesc = rs.getString("gdesc");
                grade = new Grade(gno, gname, gdesc);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeConn();
        }
        return grade;
    }

    //根据Gno删除班级
    public int deleteGradeByGno(int gno) {
        int i = 0;
        try {
            getConn();
            String sql = "delete from grade where gno='" + gno + "'";
            st = conn.createStatement();
            i = st.executeUpdate(sql);
            if (i > 0) {
                System.out.println("课程删除成功");
            } else {
                System.out.println("课程删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeConn();
        }
        return i;
    }

    //修改课程人数
    public int updateGrade(Grade grade) {
        int i = 0;
        try {
            getConn();
            String sql = getGradeSql(grade);
            st = conn.createStatement();
            i = st.executeUpdate(sql);
            if (i > 0) {
                System.out.println("grade.gcount update true");
            } else {
                System.out.println("grade.gcout update false");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeConn();
        }
        return i;
    }

    public String getGradeSql(Grade grade) {
        StringBuffer sb = new StringBuffer("update grade set");
        if (grade.getGname() != null) {
            sb.append(" gname=");
            sb.append("'");
            sb.append(grade.getGname());
            sb.append("',");
        }
        if (grade.getGdesc() != null) {
            sb.append(" gdesc='" + grade.getGdesc() + "',");
        }
        sb.append(" where gno=").append(grade.getGno());
        int index = sb.lastIndexOf(",");
        sb.replace(index, index + 1, "");
        return sb.toString();
    }

    public int addGrade(Grade grade) {
        int i = 0;
        try {
            getConn();
            String sql = "insert into grade values('" + grade.getGname() + "','" + grade.getGdesc() + "'," + grade.getGno() + ")";
            st = conn.createStatement();
            i = st.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeConn();
        }
        return i;
    }

}
